package respository

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/yyangl/yoyo/application"
	"github.com/yyangl/yoyo/models"
	"github.com/yyangl/yoyo/utils"
	"time"
)


func GetMenus (s application.Service,uid int64) ([]models.MenuModel,error){
	if s.Db() == nil {
		return nil,errors.New("databases is null")
	}
	var menus []models.MenuModel
	if s.Redis() != nil {
		res := s.Redis().Get(menusCache).Val()
		fmt.Printf("redis string %s \n",res)
		if res != "" {
			err := json.Unmarshal([]byte(res),&menus)
			if err == nil {
				return menus,nil
			}
			fmt.Printf("json unmarshal error %v\n",err)
		}
	}
	res,err := models.GetMenus(s.Db(),uid)
	fmt.Printf("get menu from db %v\n",res)
	if err != nil {
		return nil,err
	}
	menus = res
	go func() {
		bytes,err := json.Marshal(menus)
		if err != nil {
			return
		}
		s.Redis().Set(menusCache,bytes,time.Duration(cacheTime + utils.Rand(120)) * time.Second)
	}()
	return menus,nil
}
